<?php
/**
 * 队列服务类
 */

namespace app\common\lib;

class MsgQueue
{
    const ClassName = 'RabbitMq';
    private $classObj;
    /**
     * 系统内队列配置
     */
    const QUEUE_NORMAL = 'normal_queue';
    const QUEUE_ACCOUNTLOG = 'account_log';
    const QUEUE_OUTAPI_ACCESSLOG = 'out_api_accesslog';
    const QUEUE_ACCOUNT_OPTLOG = 'account_opt_log';
    const QUEUE_DELAY_NORMAL = 'delay_normal_queue';
    const QUEUE_FILE_UPLOAD = 'file_upload';
    const QUEUE_RESPONSE_LOG = 'response_log';
    const QUEUE_ERROR_LOG = 'error_log';

    private $queueName = [
        self::QUEUE_NORMAL => '普通队列',
        self::QUEUE_ACCOUNTLOG => '账号日志',
        self::QUEUE_OUTAPI_ACCESSLOG => '外部系统调用日志',
        self::QUEUE_ACCOUNT_OPTLOG => '账号操作日志',
        self::QUEUE_DELAY_NORMAL => '普通延迟消息',
        self::QUEUE_FILE_UPLOAD => '文件上传',
        self::QUEUE_RESPONSE_LOG => '请求响应日志',
        self::QUEUE_ERROR_LOG => '错误日志',
    ];

    const BIND_QUEUE_DEFAULT = 'direct_exchange';
    const BIND_QUEUE_DELAYDEFAULT = 'exchange_delay';

    /**
     * 构造方法
     * MsgQueue constructor.
     */
    function __construct()
    {
        $this->classObj = \app\common\lib\Mq\RabbitMq::instance();
    }

    /**
     * 发送消息
     * @param $queueName
     * @param string $data
     * @return bool
     */
    public function sendMessage($queueName, $data = '', $isDelay = false, $delaySecond = 0)
    {
        if (!isset($this->queueName[$queueName])) {
            return false;
        }
        $msgData = [
            'queueName' => $queueName,
            'body' => $data
        ];
        if ($isDelay) {
            $result = $this->classObj->sendDelayMessage($queueName, json_encode($msgData), $delaySecond);
        } else {
            $result = $this->classObj->sendMessage($queueName, json_encode($msgData));
        }
        if ($result['code'] != 1) {
            $this->storeFailMessage($queueName, $data);
        }
        return true;
    }

    /**
     * 存储发送失败的消息
     * @param $queuqName
     * @param $msgData
     * @return bool
     */
    private function storeFailMessage($queueName, $msgData)
    {
        $data = [];
        $data['queueName'] = $queueName;
        $data['msgData'] = json_encode($msgData);
        $data['msgData'] = addslashes($data['msgData']);
        return true;
    }

    /**
     * 接受消息
     * @param $queueName
     * @param $callback
     */
    public function receiveMesage($queueName, $callback, $isDelay = false, $bindQueueName = self::BIND_QUEUE_DEFAULT)
    {
        if ($isDelay) {
            $this->classObj->receiveMessageDelay($queueName, $callback, $bindQueueName);
        } else {
            $this->classObj->receiveMessage($queueName, $callback, $bindQueueName);
        }
    }

    /**
     * 是否需要应答
     * @return bool
     */
    static function isNeedAck()
    {
        if (self::ClassName == 'RabbitMq') {
            return true;
        }
        return false;
    }
}
